package com.killer.auth.service.impl;

import com.killer.auth.entity.AuthToken;
import com.killer.auth.service.IAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.client.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class AuthServiceImpl implements IAuthService {

    @Autowired
    private RestTemplate restTemplate;
    @Value("${server.port}")
    private int port;

    @Override
    public AuthToken login(String username, String password, String clientId, String clientSecret) {
        Map<String, Object> params = new HashMap<>();
        params.put("username", username);
        params.put("password", password);
        params.put("grant_type", "password");
        params.put("client_id", clientId);
        params.put("client_secret", clientSecret);
        //直接调用本地的即可，负载均衡交给上游服务
        String path = "http://localhost:" + port + "/oauth/token?client_id="+clientId+"&client_secret="+clientSecret
                +"&grant_type=password&username="+username+"&password="+password;
            //该请求需要对 client和clientSecret认证
            restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
                @Override
                public void handleError(ClientHttpResponse response) throws IOException {
                    byte[] body = getResponseBody(response);
                    throw new RuntimeException(new String(body));
                }
            });
            ResponseEntity<Map> result = restTemplate.exchange(path, HttpMethod.POST, null, Map.class);

            //获取响应数据
        Map   map = result.getBody();

        if (map == null || map.get("access_token") == null || map.get("refresh_token") == null || map.get("jti") == null){
            //jti是jwt令牌的唯一表示作为用户身份令牌
            throw new RuntimeException("创建令牌失效");
        }
        //将响应数据封装成AuthToken对象
        return new AuthToken((String)map.get("access_token"), (String)map.get("refresh_token"), (String)map.get("jti"));
    }

}
